package com.example.scaffold_demo.http;





import com.example.httplibrary.HttpLogger;
import com.example.scaffold_demo.http.request.RequestInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author: 李巷阳
 * Date: 2020/6/1
 * Version: V2.0.0
 * Part:
 * Description:
 */
public class ServiceGenerator {

    public static String BASE_URL = "https://t-app.moego.net";// 测试


    private static Retrofit retrofit = null;
    public static OkHttpClient httpClient;


    private static void initOkHttpClient() {
        try {
            HttpLoggingInterceptor httpLoggingInterceptor = getHttpLoggingInterceptor();
            httpClient = new OkHttpClient.Builder()
                    .addInterceptor(new RequestInterceptor())
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .addInterceptor(httpLoggingInterceptor)
                    .connectionPool(new ConnectionPool(5,6, TimeUnit.MINUTES))
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static <T> T  getApiService(final Class<T> service) {
            if (httpClient == null) {
                initOkHttpClient();
            }
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .client(httpClient)
                        .build();
            }
        return  retrofit.create(service);
    }





    /**
     * http 网络 日志输出
     * @return
     */
    public static HttpLoggingInterceptor getHttpLoggingInterceptor() {
        //日志显示级别
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLogger());
        loggingInterceptor.setLevel(level);
        return loggingInterceptor;
    }

}
